package com.gxuwz.prrs.activity;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import androidx.appcompat.app.AppCompatActivity;
import com.gxuwz.prrs.R;
import com.gxuwz.prrs.adapter.NoticeAdapter;
import com.gxuwz.prrs.bean.Notice;
import com.gxuwz.prrs.bean.Page;
import com.gxuwz.prrs.constant.Constants;
import com.gxuwz.prrs.service.impl.NoticeServiceImpl;
import com.gxuwz.prrs.utils.NavigationUtils;
import com.gxuwz.prrs.utils.PageUtils;

import java.util.LinkedList;
import java.util.List;

/**
 * @author 张钧
 * 通知列表页
 */
public class NoticesActivity extends AppCompatActivity {

	List<Button> buttonList = new LinkedList<>();

	NoticeAdapter noticeAdapter;
	ImageView left;
	ImageView right;

	long current = 1;
	long size = 6;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_notices);
		NavigationUtils.setRedirectBottom(this);
		left = findViewById(R.id.left);
		right = findViewById(R.id.right);
		NavigationUtils.setBack(R.id.back,this);
		//加载页码导航
		PageUtils.setupPageButtons(this, buttonList, this::onClick);
		//加载第一页的公告数据
		List<Notice> noticeList = loadPage(1);
		if (noticeList != null) {
			noticeAdapter = new NoticeAdapter(this, noticeList);
			ListView listView = findViewById(R.id.notices_list_view);
			listView.setAdapter(noticeAdapter);
			listView.setOnItemClickListener((parent, view, position, id) -> {
				Notice item = noticeAdapter.getItem(position);
				Bundle bundle = new Bundle();
				bundle.putString(Constants.TITLE, item.getTitle());
				bundle.putString(Constants.CONTENT, item.getContent());
				bundle.putString(Constants.NOTICE_TIME, item.getNoticeTime());
				NavigationUtils.redirectToNoticeDetailActivity(NoticesActivity.this, bundle);
			});
		}
		//加载左右按钮导航
		Page<Notice> p = new Page<>();
		p.setSize(size);
		PageUtils.setupNavigationButtons(this, buttonList, left, right, current, noticeAdapter, NoticeServiceImpl.class, p);
	}

	/**
	 * 按钮点击事件
	 *
	 * @param view 按钮
	 */
	private void onClick(View view) {
		Button button = (Button) view;
		long aim = Long.parseLong(String.valueOf(button.getText()));
		noticeAdapter.updateData(loadPage(aim));
	}

	/**
	 * 加载页面
	 *
	 * @param current 目标页
	 * @return 页面数据
	 */
	private List<Notice> loadPage(long current) {
		Page<Notice> p = new Page<>();
		p.setSize(size);
		List<Notice> noticeList = PageUtils.loadPage(this, current, noticeAdapter, NoticeServiceImpl.class, p, buttonList, left, right);
		this.current = current;
		return noticeList;
	}
}
